import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import axios from "axios";
import VueAxios from "vue-axios";
import Navigation from "vue-navigation";
import VueWechatTitle from "vue-wechat-title";
import jquery from "jquery";
import "vant/lib/icon/local.css";
import VueAMap from "vue-amap";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import VueKeyCloak from "@dsb-norge/vue-keycloak-js";
// 在入口文件中（main.js），导入组件库
import vueHashCalendar from "vue-hash-calendar";
// 引入组件CSS样式
import "vue-hash-calendar/lib/vue-hash-calendar.css";
import "@/iconfont/iconfont.css";
import { Toast, NoticeBar, Popover } from "vant";
Vue.use(NoticeBar);
Vue.use(Popover);
import PortalVue from "portal-vue";

Vue.use(PortalVue);

// import VxeUIAll from 'vxe-pc-ui'
// import 'vxe-pc-ui/lib/style.css'
import VxeUITable from "vxe-table";
import "vxe-table/lib/style.css";

// Vue.use(VxeUIAll)
Vue.use(VxeUITable);

// import VConsole from 'vconsole'
// const vConsole = new VConsole({
//   theme: 'dark',
//   onReady: () => {
//     //console.log('vConsole is ready.')
//   }
// })

Vue.use(VueAMap).use(ElementUI).use(vueHashCalendar);
// Vue.use(ElementUI).use(vueHashCalendar)
Vue.prototype.$ = jquery;
VueAMap.initAMapApiLoader({
  key: "86b81050865c1ef0c86c272b85f9a7e4",
  // key: 'e762e8d8003a79d26ece5f84b4afbfb0',
  // key: 'd240b5ef41735612e86a911a335812fb',
  plugin: ["Autocomplete", "PlaceSearch", "Geolocation", "ToolBar", "Geocoder"],
  uiVersion: "1.0",
});
Vue.config.productionTip = false;

Vue.use(VueAxios, axios).use(Navigation, { router, store }).use(VueWechatTitle);
let routeList = router.options.routes;
const jsonData = require("./project.json");
let project = jsonData.project;

// //console.log(project)
// //console.log(routeList)

let crmtitle = jsonData["default/"].crmtitle;
if (jsonData[project] !== undefined) {
  crmtitle = jsonData[project].crmtitle;
}
router.beforeEach((to, from, next) => {
  // XXX: 修复iOS版微信HTML5 History兼容性问题
  //console.log('to', to)
  //console.log('location.pathname', location.pathname)
  // if ( to.path !== location.pathname) {
  //   // 此处不可使用location.replace
  //   location.assign(to.fullPath)
  // }
  //console.log('beforeeach location', location)
  /* 路由发生变化修改页面title */
  if (to.query.stitle) {
    document.title = to.query.stitle;
  } else {
    document.title = crmtitle;
  }
  //console.log('document.title', document.title)
  for (let i = 0; i < routeList.length; i++) {
    if (routeList[i].name === project + to.name) {
      router.push({
        name: project + to.name,
        query: to.query,
        params: to.params,
      });
      return;
    }
  }
  next();
});

let projectData = require("@/project.json");
if (projectData.project && projectData.project == "dinuo/") {
  let configData = require("@/json/dinuoconfig.json");
  //console.log('dinuo..', 'vuekeycloak')
  Vue.use(VueKeyCloak, {
    init: {
      onLoad: "login-required",
      checkLoginIframe: false,
    },
    config: {
      realm: "dinuo",
      url: configData.authURL,
      // url: 'https://passport.dinuo.com.cn/auth',
      clientId: "jkb-crm-pages",
    },
    onReady: (kc) => {
      //console.log('kc', kc.token)
      new Vue({
        router,
        store,
        render: (h) => h(App),
      }).$mount("#app");
    },
  });
} else {
  new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount("#app");
}

Vue.mixin({
  created() {
    // 全局响应拦截器
    axios.interceptors.response.use(
      (response) => {
        // if (response.data.flag === "1") {
        //   Toast(response.data.des);
        //   if (response.data.des && response.data.des.indexOf("登录过期") >= 0) {
        //     this.loginout();
        //   }
        // }
        // 判断是否返回的是登录的HTML
        if (
          typeof response.data === "string" &&
          (response.data.includes("<html") ||
            response.data.includes("<!DOCTYPE html>"))
        ) {
          if (response.data.includes("忘记密码")) {
            this.loginout();
          }
          // 重新抛出异常
          return Promise.reject({
            isHtmlResponse: true,
            data: response.data,
          });
        }

        return response;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  },
  methods: {
    reserror(res) {
      if (res.isHtmlResponse) return;
      Toast("系统异常，请联系管理员！");
    },
    loginout() {
      let ua = window.navigator.userAgent.toLowerCase();
      if (ua.indexOf("wxwork") !== -1) {
        this.logintype = "wxwork";
      } else if (ua.indexOf("dingtalk") !== -1) {
        this.logintype = "dingding";
      } else if (ua.indexOf("micromessenger") !== -1) {
        this.logintype = "wechat";
      } else if (ua.indexOf("tenantid") !== -1) {
        // 友空间
        this.logintype = "ykj";
      } else {
        this.logintype = "nosass";
      }
      // 非sass模式
      let projectData = require("@/project.json");
      // //console.log('projectData', projectData)
      if (projectData.project && projectData.project == "dinuo/") {
        //console.log(' inter logtype:', 'nosass')
        this.axios({
          method: "post",
          url: "/nosaaslogout",
          data: {},
        })
          .then((res) => {
            //console.log(res)
            if (res.data.tsxx == "ok") {
              //console.log('inner...', res.tsxx)
              //console.log('url', window.location.href)
              window.location.href = "/";
            }
          })
          .catch((res) => {
            this.reserror(res);
          });
        return;
      }
      this.axios({
        method: "post",
        url: "/api/login.loginout.do",
        data: {},
      })
        .then((res) => {
          if (res.data.flag === "1") {
            Toast(res.data.des);
          } else {
            this.$router.push({ name: "home" });
          }
        })
        .catch((res) => {
          this.reserror(res);
        });
    },
  },
});
